package com.ncwu.infrastructure.exception;

import com.ncwu.interfaces.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : wuwensheng
 * @date : 15:54 2020/5/29
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * 拦截业务异常，返回业务异常信息
     * @param exception 异常
     * @return Result
     */
    @ExceptionHandler(CmdcException.class)
    public Result handleBusinessError(CmdcException exception) {
        int code = exception.getCode();
        String message = exception.getMessage();
        return new Result(code, message);
    }


    @ExceptionHandler
    public Result<ErrorEnum> ErrorHandler(AuthorizationException e) {
        log.error("权限校验失败！", e);
        return new Result<>(ErrorEnum.NO_AUTH.getCode(),ErrorEnum.NO_AUTH.getMsg());
    }


    @ExceptionHandler
    public Result ErrorHandler(AuthenticationException e) {
        log.error("登录失败！", e);
        return new Result<>(ErrorEnum.ERROR_ACCOUNT.getCode(),e.getMessage());
    }

    @ExceptionHandler
    public Result errorHandler(IncorrectCredentialsException e) {
        log.error("用户名或密码错误,用户登录失败！", e);
        return new Result<>(ErrorEnum.ERROR_ACCOUNT.getCode(), ErrorEnum.ERROR_ACCOUNT.getMsg());
    }

    /**
     * 参数校验错误异常处理
     *
     * @param e 异常
     * @return Result
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result NotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.debug("异常详情 ", e);
        return new Result<>(ErrorEnum.METHOD_ARGUMENT_NOT_VALID.getCode(), getError(e.getBindingResult().getAllErrors()));
    }

    private String getError(List<ObjectError> allErrors) {
        List<String> message = allErrors.stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());
        return message.toString();
    }

    @ExceptionHandler
    public Result errorHandler(Exception e) {
        log.info("异常:{}", e);
        return new Result<>(400,e.getMessage());
    }
}
